import AdvisementModel from "../../../database/models/advisement";

export const typeDefs = `
type Advisement{
  _id: String!
  title: String!
  content: String
  from: Player!
  phoneNum: String!
  qqNum: String!
  state: String!
  reply: String
  createAt: String!
  updateAt: String!
}

input ReplyInput {
  reply: String!
  state: String!
  updateAt: String!
 }
`

export const queryDefs = `
  getAdvisements(state: [String!], page: Int!, size: Int, query: String): [Advisement]!
`

export const mutationDefs = `
  replyAdvisement(_id:String!, replyInput: ReplyInput!): Advisement!
  updateState(_id:String!, state: String!): Boolean!
  `

export const resolvers = {
  Query: {
    getAdvisements: async (_, {state, page, size = 20, query = ''}) => {
      const reg = new RegExp(query, 'gi')
      const ads = await AdvisementModel.find({content: reg, state: {$in: state}}).sort({state: -1, createAt: 1})
        .skip(size * page).limit(size).populate(`from`).lean()
      return ads
    },
  },
  Mutation: {
    replyAdvisement: async (_, {_id, replyInput: {reply, state, updateAt}}) => {
      const advisement =
        await AdvisementModel.findByIdAndUpdate(_id, {reply, state, updateAt: new Date(updateAt)}, {new: true})
      return advisement
    },
    updateState: async (_, {_id, state}) => {
      const updateAt = new Date()
      const advisement = await AdvisementModel.findByIdAndUpdate(_id, {state, updateAt}, {new: true})
      return !!advisement
    }
  }
}
